#include "gd32f4xx_it.h"
#include "systick.h"

uint8_t DACBlockCount = 0;                    //响铃为音乐时记录使用的第几个数据块 

/*!
    \brief      this function handles HardFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void HardFault_Handler(void)
{
    /* if Hard Fault exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles MemManage exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void MemManage_Handler(void)
{
    /* if Memory Manage exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles BusFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void BusFault_Handler(void)
{
    /* if Bus Fault exception occurs, go to infinite loop */
    while (1);
}

/*!
    \brief      this function handles UsageFault exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void UsageFault_Handler(void)
{
    /* if Usage Fault exception occurs, go to infinite loop */
    while (1);
}


/*!
    \brief      this function handles SysTick exception
    \param[in]  none
    \param[out] none
    \retval     none
*/
void SysTick_Handler(void)
{
    timer_event_software_generate(TIMER0,TIMER_EVENT_SRC_CMTG);
}

void DMA0_Channel5_IRQHandler(void)
{
	 if(dma_interrupt_flag_get(DMA0, DMA_CH5, DMA_INT_FLAG_FTF)) 
	 {
			if(DACBlockCount == 9)
			{
				dma_interrupt_flag_clear(DMA0, DMA_CH5, DMA_INT_FLAG_FTF);
				return;
			}
			DACBlockCount++;
		 	dma_flag_clear(DMA0, DMA_CH5, DMA_INT_FLAG_FTF);  // 清除传输完成标志
			dma_flag_clear(DMA0, DMA_CH5, DMA_INT_FLAG_FEE);  // 清除错误标志
		  	timer_disable(TIMER5);
			dma_channel_disable(DMA0,DMA_CH5);
		 	dac_dma_disable(DAC0);
			dac_disable(DAC0);
		  
		  	if(DACBlockCount == 3)
			{
				dma_transfer_number_config(DMA0, DMA_CH5, 0x846B);
			}
			else
			{
				dma_transfer_number_config(DMA0, DMA_CH5, 0xFFFF);
			}
			Test_Order_sign(1);
			dma_memory_address_config(DMA0, DMA_CH5,DMA_MEMORY_0,((uint32_t)0x08040000 + 0xFFFF*DACBlockCount));
		  	dma_channel_enable(DMA0, DMA_CH5); 
		  	dac_dma_enable(DAC0);
			dac_enable(DAC0);
			timer_enable(TIMER5);
			dma_interrupt_flag_clear(DMA0, DMA_CH5, DMA_INT_FLAG_FTF);
   }
	 
	 if(DACBlockCount >  2)
	 {
		 DACBlockCount = 0;
	 }
}

void DAC_Block_Count_Set(uint8_t value)
{
	DACBlockCount = value;
}